var express = require('express');
const sqlQuery = require('../../model/HGmysql');
//验证码模块
const getCaptcha = require('../../model/yzm');
// 引入给密码加密的方法、token密钥、过期时间
import { PWD_SALT, PRIVATE_KEY, EXPIRESD } from '../../model/utils/constant'
    // 引入处理token的方法
const jwt = require('jsonwebtoken')

var router = express.Router();
//图形验证码
router.get('/captcha', (req, res, next) => {
    getCaptcha(req, res, next)
});
/* 登录接口 */
router.post('/login', async(req, res, next) => {
        let { username, password, yzm } = req.body
        try {
            // 查询有无username
            let user = await sqlQuery('select * from user where username = ?', [username]);
            if (!user || user.length === 0) {
                // 如果查不到该账号
                res.send({ code: -1, msg: '该账号不存在' })
            } else {
                if (yzm != req.session.cap) {
                    return res.send({ code: -1, msg: '验证码错误(小写字母)' })
                }
                let result = await sqlQuery('select * from user where username = ? and password = ?', [username, password])
                    // 如果该结果不存在，则显示密码或账号不正确
                if (!result || result.length === 0) {
                    res.send({ code: -1, msg: '账号或密码不正确' })
                } else {
                    // 如果该结果存在说明登录成功，则生成token
                    let token = jwt.sign({ username }, PRIVATE_KEY, { expiresIn: EXPIRESD })
                    res.send({ code: 0, msg: '登录成功', token })
                }
            }
        } catch (e) {
            console.log(e);
            // 把错误交给错误中间件处理
            next(e)
        }
    })
    /* 获取用户信息 */
router.get('/info', async(req, res, next) => {
    // 这个req是经过了 expressJwt拦截token 后得到的对象  req.user可得到解密后的token信息
    console.log(req.user);
    let { username } = req.user
    try {
        let userinfo = await sqlQuery('select nickname,head_img from user where username = ?', [username])
        res.send({ code: 0, msg: '成功', data: userinfo[0] })
    } catch (e) {
        console.log(e);
        next(e)
    }
});
//头像更换
router.post('/uploader', async(req, res) => {
    //解析前台formdata
    console.log(req.files);
    try {
        var imgData = req.files.picFile
            //token解析
       let username = req.user.username
        console.log(username);
       let path = `public/upload/` + req.files.picFile.md5 + Date.now() + '.jpg'
       let paths = `http://localhost:4000${path.slice(6)}`
        imgData.mv(path, async function(err) {
            if (err) {
                return res.status(500).send(err);
            } else {
                let strSql = `update user set head_img='${paths}' where username = '${username}'`
                let result = await sqlQuery(strSql);
                return res.send({
                    message: 'ok',
                    file: paths
                });
            }
        });
    } catch (error) {
        console.log(error);
        res.send({
            message: '上传失败',

        });
    }
})
module.exports = router;